﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Dapper;
using DapperExtensions;

namespace Agile.Service.Rbac {
    ///<summary>
    ///角色表
    ///</summary>
    public interface IRoleService:IRepository<Role> {
        void Switch(string Id);
        List<Role> GetRoles(string keyword = "");
        Result SubmitForm(RoleReq roleReq);
        List<TreeViewModel> GetMenuElementTree(string roleId);
        List<TreeViewModel> GetBranTree(string roleId);
    }
    ///<summary>
    ///角色表
    ///</summary>
    public partial class RoleService:BaseRepository<Role>, IRoleService {

        private readonly IRelevanceService _relevanceService;
        public RoleService(IRelevanceService relevanceService) {
            _relevanceService = relevanceService;
        }
        public List<TreeViewModel> GetMenuElementTree(string roleId) {
            var table = DBA.ExecuteDataTable(@"SELECT ID,ParentID,Name FROM(
SELECT ID,ParentID,Name,OrderBy FROM [rbac_menu] WHERE [Status]=0 
union all
SELECT ID,[ModuleId] AS ParentID,Name,OrderBy FROM [rbac_menuelement] WHERE 
ModuleId IN(SELECT ID FROM [rbac_menu] WHERE [Status]=0)
)d ORDER BY OrderBy");
            var treeList = new List<TreeViewModel>();
            foreach(DataRow row in table.Rows) {
                string SecondId = DBA.ExecuteScalar<string>("SELECT SecondId FROM [dbo].[base_relevance] WHERE [Key] IN('RoleElement','RoleModule') AND FirstId='" + roleId + "' AND SecondId='" + row["ID"].ToString() + "'");
                TreeViewModel tree = new TreeViewModel();
                bool hasChildren = table.Select("ParentID='" + row["ID"].ToString() + "'").Length == 0 ? false : true;
                tree.id = row["ID"].ToString();
                tree.text = row["Name"].ToString();
                tree.value = row["ID"].ToString();
                tree.parentId = row["ParentID"].ToString();
                tree.isexpand = false;
                tree.complete = true;
                tree.checkstate = !string.IsNullOrWhiteSpace(SecondId) ? 1 : 0;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return treeList;
        }
        public List<TreeViewModel> GetBranTree(string roleId) {
            var table = DBA.ExecuteDataTable(@"SELECT ID,ParentID,Name FROM [dbo].[rbac_organize] WHERE [Status]=0 ORDER BY OrderBy");
            var treeList = new List<TreeViewModel>();
            foreach(DataRow row in table.Rows) {
                string SecondId = DBA.ExecuteScalar<string>("SELECT SecondId FROM [dbo].[base_relevance] WHERE [Key] IN('RoleOrg') AND FirstId='" + roleId + "'  AND SecondId='"+ row["ID"].ToString() + "'");
                TreeViewModel tree = new TreeViewModel();
                bool hasChildren = table.Select("ParentID='" + row["ID"].ToString() + "'").Length == 0 ? false : true;
                tree.id = row["ID"].ToString();
                tree.text = row["Name"].ToString();
                tree.value = row["ID"].ToString();
                tree.parentId = row["ParentID"].ToString();
                tree.isexpand = false;
                tree.complete = true;
                tree.checkstate = !string.IsNullOrWhiteSpace(SecondId) ? 1 : 0;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return treeList;
        }
        public List<Role> GetRoles(string keyword = "") {
            string where = " Category=1 ";
            if(!string.IsNullOrEmpty(keyword)) {
                where = " and (Name='" + keyword + "' or EnCode='" + keyword + "')";
            }
            var data = FindAll(where).ToList();
            return data;
        }
        public Result SubmitForm(RoleReq roleReq) {
            Result result = new Result(true);
            string[] permissionIdArr;
            //菜单
            if(!string.IsNullOrWhiteSpace(roleReq.PermissionMenus)) {
                permissionIdArr = roleReq.PermissionMenus.Split(',');
                if(permissionIdArr.Length > 0) {
                    List<string> moduleids = new List<string>();
                    List<string> buttionids = new List<string>();
                    _relevanceService.UnAssign(new AssignReq { type = Define.ROLEMODULE,firstId = roleReq.ID });
                    _relevanceService.UnAssign(new AssignReq { type = Define.ROLEELEMENT,firstId = roleReq.ID });
                    foreach(var itemId in permissionIdArr) {
                        if(itemId == "undefined") continue;
                        var vitemId = itemId;
                        int hasChildren = vitemId.Split('#').Length > 1 ? 5 : 1;
                        if(hasChildren == 5) {
                            //按钮权限
                            buttionids.Add(itemId.Replace("#",""));
                        } else {
                            //菜单权限
                            moduleids.Add(itemId);
                        }
                    }
                    _relevanceService.Assign(new AssignReq { type = Define.ROLEMODULE,firstId = roleReq.ID,secIds = moduleids.ToArray() });
                    _relevanceService.Assign(new AssignReq { type = Define.ROLEELEMENT,firstId = roleReq.ID,secIds = buttionids.ToArray() });
                }
            }
            //组织
            if(!string.IsNullOrWhiteSpace(roleReq.PermissionOrganizes)) {
                permissionIdArr = roleReq.PermissionMenus.Split(',');
                if(permissionIdArr.Length > 0) {
                    _relevanceService.UnAssign(new AssignReq { type = Define.ROLEORG,firstId = roleReq.ID });
                    List<string> powerids = new List<string>();
                    foreach(var itemId in permissionIdArr) {
                        if(itemId == "undefined") continue;
                        powerids.Add(itemId);
                    }
                    _relevanceService.Assign(new AssignReq { type = Define.ROLEORG,firstId = roleReq.ID,secIds = powerids.ToArray() });
                }
            }
            //数据

            this.AddOrUpdate(roleReq);
            return result;
        }
        public void Switch(string Id) {
            var model = Find(Id);
            if(model != null) {
                if(model.Status > 0) {
                    model.Status = 0;
                } else {
                    model.Status = 1;
                }
                Update(model);
            }
        }
    }
}

